package com.smallyu.order.filter;

import com.smallyu.order.config.YuExcludeRequestURI;
import com.smallyu.order.constant.YuConstants;
import com.smallyu.order.exception.YuTokenException;
import com.smallyu.order.utils.YuJwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @Author: small-yu
 * @Package: com.smallyu.order.filter
 * @Project: order
 * @Date: 2024/4/9
 * @Time: 23:41
 */
@Component
public class YuFilter implements Filter {

    @Autowired
    private YuJwtUtils yuJwtUtils;

    @Autowired
    private YuExcludeRequestURI yuExcludeRequestURI;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        String requestURI = request.getRequestURI();
        //排除特定请求
        if (yuExcludeRequestURI.excludeUri().contains(requestURI)){
            filterChain.doFilter(request,servletResponse);
            return;
        }
        String token = request.getHeader(YuConstants.TOKEN);
        //携带token
//        if (!StringUtils.isEmpty(token)){
            try{
                yuJwtUtils.verifyToken(token);
                filterChain.doFilter(request,servletResponse);
//            }catch (SignatureVerificationException e){
//                e.printStackTrace();
////                map.put("msg","无效签名");
//            }catch (TokenExpiredException e){
//                e.printStackTrace();
////                map.put("msg","签名过期");
            }catch (Exception e){
                e.printStackTrace();
                throw new YuTokenException("token失效,无访问权限");
            }
//        }
        return;
    }
}
